//------------------------------------------------------------ // Purpose: Program to calculate Taylors series approximations // of sin(x) and cos(x) with varying number of terms. // Author: John Gauch //------------------------------------------------------------ #include #include using namespace std; int main() { // Initialize variables float X = 0.1; float sinX = 0.0; float cosX = 1.0; float XtoN = 1.0; float Nfact = 1.0; // Loop to calculate sin and cos for (int N = 1; N <= 7; N++) { // Calculate Taylor series term cout << "N:\t" << N << endl; XtoN = XtoN * X; cout << "XtoN:\t" << XtoN << endl; Nfact = Nfact * N; cout << "Nfact:\t" << Nfact << endl; // Calculate sin value if (N % 4 == 1) sinX = sinX + XtoN/Nfact; if (N % 4 == 3) sinX = sinX - XtoN/Nfact; cout << "sinX:\t" << sinX << endl; cout << "truth:\t" << sin(X) << endl; cout << "error:\t" << sinX - sin(X) << endl; // Calculate cos value if (N % 4 == 0) cosX = cosX + XtoN/Nfact; if (N % 4 == 2) cosX = cosX - XtoN/Nfact; cout << "cosX:\t" << cosX << endl; cout << "truth:\t" << cos(X) << endl; cout << "error:\t" << cosX - cos(X) << endl; cout << endl; } }